﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using _1Dot9MasterBiz;
using System.Collections;
using _1Dot9MasterCommon;

public partial class Admin_Login : System.Web.UI.Page
{
    private string strUserId = "";
    private string strUserPw = "";
    private DataSet dsUser = null;
    
    /// <summary>
    /// 페이지 로드
    /// </summary>    
    protected void Page_Load(object sender, EventArgs e)
    {
        dsUser = new DataSet();
    }

    /// <summary>
    /// 로그인 버튼 클릭 이벤트
    /// </summary>    
    protected void btnLogin_Click(object sender, ImageClickEventArgs e)
    {
        strUserId = this.txtId.Text.Trim();
        strUserPw = this.txtPw.Text.Trim();

        if (CheckLoginUser(strUserId) < 1)
        {
            Response.Write("<script> alert('해당 관리자가 없습니다. ID를 확인하세요.'); </script>");
            return;
        }

        if (!CheckUserPw(strUserPw))
        {
            this.txtPw.Focus();
            return;
        }
        
        this.SetUserProfile();        
        this.Response.Redirect(string.Format("AdminUserInfo.aspx"));
    }

    /// <summary>
    /// 어드민 유저 DB 조회
    /// </summary>    
    protected int CheckLoginUser(string _id)
    {  
        try
        {
            using (AdminBiz adminBiz = new AdminBiz())
            {
                Hashtable htParams = new Hashtable();
                htParams.Add("@P_USER_ID", _id);

                dsUser = adminBiz.GetAdminUser(htParams);
                return dsUser.Tables[0].Rows.Count;
            }
        }
        catch (Exception ex)
        {
            _1Dot9MasterCommon.CommonLogger.LogException(
                "Login.aspx.cs >> protected int CheckLoginUser(string _id)",
                ex.ToString(),
                false);
            return 0;
        }
    }

    /// <summary>
    /// 관리자 비밀번호 체크 메소드
    /// </summary>
    /// <returns></returns>
    protected bool CheckUserPw(string _pw)
    {
        CryptoUtil crypto = new CryptoUtil();

        string descryptoPw = crypto.AESDecrypt256(dsUser.Tables[0].Rows[0]["USER_PW"].ToString());

        if (!descryptoPw.Equals(_pw))
        {
            Response.Write("<script> alert('비밀 번호가 맞지 않습니다. 확인하세요.'); </script>");
            return false;
        }
            
        return true;
    }

    /// <summary>
    /// 로그인 정보를 등록한다.
    /// </summary>
    protected void SetUserProfile()
    {
        UserInfo.UserId = dsUser.Tables[0].Rows[0]["USER_ID"].ToString();
        UserInfo.UserName = dsUser.Tables[0].Rows[0]["NAME"].ToString();
        UserInfo.UserEmail = dsUser.Tables[0].Rows[0]["EMAIL"].ToString();
        UserInfo.UserPhone = dsUser.Tables[0].Rows[0]["PHONE"].ToString();
    }
}